//
//  WFPictureViewController.m
//  谷居
//
//  Created by dllo on 16/6/16.
//  Copyright © 2016年 刘万方. All rights reserved.
//

#import "WFPictureViewController.h"
#import "WFNavigationView.h"
#import "WFLabel.h"
#import "AFNetworking.h"
#import "NetWorkingTool.h"
#import "YJPCycleView.h"
#import "WFHandleURL.h"


#import "WFPIcsCell.h"
#import "WFCollectionViewLayout.h"


#import "WFColorModel.h"
#import "WFStyleModel.h"
#import "WFSpaceModel.h"
#import "WFMapModel.h"

#import "MJRefresh.h"

#import "WFPicScrollVC.h"
@interface WFPictureViewController ()
<
YJPCycleViewDelegate,
WFCollectionLayoutDelegate,
UICollectionViewDataSource,
UICollectionViewDelegate,
WFNavigationViewDelegate
>
@property (nonatomic, retain) WFNavigationView *navigationView;

@property (nonatomic, retain) UIImageView *hairlineImageViewUnder;

@property (nonatomic, retain) UIButton *photoButton; /** 头像. */

@property (nonatomic, retain) WFLabel *titleLabel;

@property (nonatomic, retain) UICollectionView *picCollectionView; /** 瀑布流. */

@property (nonatomic, retain) NSMutableArray *picArray;

@property (nonatomic, retain) NSMutableArray *colorArray;

@property (nonatomic, retain) NSMutableArray *styleArray;

@property (nonatomic, retain) NSMutableArray *spaceArray;

@property (nonatomic, retain) NSMutableArray *mapArray;

/** 关于网络请求的参数. */
@property (nonatomic, assign) NSInteger start;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, assign) NSInteger sortId;

@property (nonatomic, assign) NSInteger userId;

@property (nonatomic, assign) NSInteger space;

@property (nonatomic, assign) NSInteger style;

@property (nonatomic, assign) NSInteger color;


@end

@implementation WFPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavigationView];
    
    /** 网络请求. */
    [self refresh];
//    NSString *url = [WFHandleURL picsHandleURLWithSortId:self.sortId start:self.start count:self.count userId:self.userId space:self.space style:self.style color:self.color];
//    [self makeRequestWtihUrl:url upDown:YES];
    [self createCollectionView];
}

#pragma mark - 懒加载

- (NSInteger)start {
    if (!_start) {
        _start = 0;
    }
    return _start;
}

- (NSInteger)count {
    if (!_count) {
        _count = 10;
    }
    return _count;
}

- (NSInteger)sortId {
    if (!_sortId) {
        _sortId = 2;
    }
    return _sortId;
}

- (NSInteger)userId {
    if (!_userId) {
        _userId = 0;
    }
    return _userId;
}

- (NSInteger)space {
    if (!_space) {
        _space = 0;
    }
    return _space;
}

- (NSInteger)style {
    if (!_style) {
        _style = 0;
    }
    return _style;
}

-(NSInteger)color {
    if (!_color) {
        _color = 0;
    }
    return _color;
}

- (NSMutableArray *)picArray {
    if (_picArray == nil) {
        _picArray = [[NSMutableArray array] retain];
    }
    return _picArray;
}
#pragma mark - 网络请求
- (void)makeRequestWtihUrl:(NSString *)url upDown:(BOOL)upDown {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /** 创建瀑布流. */
        NSArray *photosArr = responseObject[@"photos"];
        if (upDown) {
            [self.picArray removeAllObjects];
            self.picArray = [WFPhotosModel baseModelByArray:photosArr];
            [_picCollectionView reloadData];

        } else {
            NSMutableArray *arr = [WFPhotosModel baseModelByArray:photosArr];
            [self.picArray addObjectsFromArray:arr];
        }
        [_picCollectionView reloadData];

        NSLog(@"%@", self.picArray);
        NSLog(@"%ld", self.picArray.count);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}



#pragma mark - 创建瀑布流
                                                                        - (void)createCollectionView {
    WFCollectionViewLayout *layout = [[WFCollectionViewLayout alloc] init];
    layout.columnCounts = 2;
    layout.columnSpace = 20;
    layout.rowSpace = 15;
    layout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.delegate = self;
    
    _picCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 68-44) collectionViewLayout:layout];
    [self.view addSubview:_picCollectionView];
    [_picCollectionView release];
    _picCollectionView.delegate = self;
    _picCollectionView.dataSource = self;
    
    [_picCollectionView registerClass:[WFPIcsCell class] forCellWithReuseIdentifier:@"picsCell"];
    
    
#pragma mark - 加载上拉 \ 下拉刷新.
    _picCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    _picCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
}


- (void)refresh {
    self.start = 0;
    
    NSString *url = [WFHandleURL picsHandleURLWithSortId:self.sortId start:self.start count:self.count userId:self.userId space:self.space style:self.style color:self.color];
    [self makeRequestWtihUrl:url upDown:YES];
    [_picCollectionView.mj_header endRefreshing];

}

- (void)loadMore {
    self.start += 10;
    NSString *url = [WFHandleURL picsHandleURLWithSortId:self.sortId start:self.start count:self.count userId:self.userId space:self.space style:self.style color:self.color];
    
    [self makeRequestWtihUrl:url upDown:NO];
    [_picCollectionView.mj_footer endRefreshing];

    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.picArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WFPIcsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"picsCell" forIndexPath:indexPath];
    
    WFPhotosModel *photoModel = self.picArray[indexPath.row];
    cell.photoModel = photoModel;
    return cell;
}
- (CGFloat)layout:(WFCollectionViewLayout *)layout heightFroItenAtIndexPath:(NSIndexPath *)indexPath Width:(CGFloat)widthh {
    WFPhotosModel *model = self.picArray[indexPath.row];
    
    CGFloat height = widthh * model.height / model.width;
    return height;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    WFPicScrollVC  *vc = [[WFPicScrollVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    vc.picArray = self.picArray;
    vc.index = indexPath.row;
    [vc release];
    
}


#pragma mark - 创建导航栏
- (void)createNavigationView {
    _navigationView = [[WFNavigationView alloc] initWithFrame:NA_FRAME];
    [self.view addSubview:_navigationView];
    [_navigationView release];
    _navigationView.backgroundColor = [UIColor yellowColor];
    _navigationView.buttonCount = 3;
    _navigationView.navigationType = 1;
    
    
    /** 签订协议. */
    _navigationView.delegate = self;
    
    self.colorArray = [NSMutableArray array];
    self.spaceArray = [NSMutableArray array];
    self.styleArray = [NSMutableArray array];
//    self.mapArray = [NSMutableArray array];
    
    NSString *urlStr = @"http://api.guju.com.cn/v2/photo/map";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.colorArray = [WFColorModel baseModelByArray:responseObject[@"color"]];
        self.spaceArray = [WFSpaceModel baseModelByArray:responseObject[@"space"]];
        self.styleArray = [WFStyleModel baseModelByArray:responseObject[@"style"]];
        WFMapModel *mapModel = [[WFMapModel alloc] init];
        [mapModel setValuesForKeysWithDictionary:responseObject];
        [self.mapArray addObject:mapModel];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
//    [_navigationView createTitleView];
    
    
    _hairlineImageViewUnder = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    /** 创建titleLabel. */
    [self createTitleLabel];
    
    
    
}


- (void)backTorefreshTableViewWithId:(NSString *)_id indexType:(NSInteger)type {
    switch (type) {
        case 0:
            self.space = _id.integerValue;
            break;
            case 1:
            self.style = _id.integerValue;
            break;
            case 2:
            self.color = _id.integerValue;
            break;
        default:
            break;
    }
    [self refresh];
}


- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0 ) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
    
}


- (void)createTitleLabel {
    _titleLabel = [[WFLabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    self.navigationItem.titleView = _titleLabel;
    //    _titleLabel.backgroundColor = [UIColor whiteColor];
    _titleLabel.text = @"图库";
    _titleLabel.textAlignment = 1;
}
- (void)viewDidAppear:(BOOL)animated {
    SYMBOL = @1;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"symbolChange" object:nil];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _hairlineImageViewUnder.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [super viewDidAppear:animated];
    
}

- (void)setMapArray:(NSMutableArray *)mapArray {
    if (_mapArray != mapArray) {
        [_mapArray release];
        _mapArray = [[NSMutableArray array]retain];
    }
}
- (void)dealloc {
//    [_colorArray release];
//    [_spaceArray release];
//    [_styleArray release];
//    [_mapArray release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
